<script setup lang="ts">
import type { MenuOption } from 'sard-uniapp'
import i18n from '@/locale'

// 支持的语言选项
const languageOptions: MenuOption[] = [
  {
    text: '简体中文',
    value: 'zh-Hans',
  },
  {
    text: 'English',
    value: 'en',
  },
]

// 获取当前语言
const currentLocale = ref(uni.getLocale())

// 获取当前语言的显示文本
function getCurrentLanguageText() {
  const current = languageOptions.find(option => option.value === currentLocale.value)
  return current?.text || '简体中文'
}

// 语言切换处理
function onLanguageSelect(option: MenuOption) {
  const newLocale = option.value as string
  uni.setLocale(newLocale)

  // 同步更新 i18n 全局实例的语言，确保 $t 立即生效
  try {
    const globalI18n: any = i18n.global
    if (typeof globalI18n.locale === 'string') {
      globalI18n.locale = newLocale
    }
    else if (globalI18n.locale && 'value' in globalI18n.locale) {
      globalI18n.locale.value = newLocale
    }
  }
  catch (e) {
    console.error('更新 i18n.global.locale 失败:', e)
  }

  // 更新本地状态
  currentLocale.value = newLocale
  // 显示切换成功提示
  const toastTitle = newLocale === 'en' ? 'Language switched successfully' : '语言切换成功'

  uni.showToast({
    title: toastTitle,
    icon: 'success',
    duration: 800,
  })

  // 不再重启页面，直接依靠 i18n 的响应式更新 UI
}
</script>

<template>
  <sar-popover :options="languageOptions" @select="onLanguageSelect">
    <sar-popover-reference>
      <view class="flex items-center justify-center rounded-full bg-white/20 p-2 backdrop-blur-sm">
        <view class="i-carbon-ibm-watson-language-translator text-lg text-#000" />
      </view>
    </sar-popover-reference>
  </sar-popover>
</template>

<style scoped>
/* 组件样式 */
</style>
